package com.everbest.admin.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ThreadLocalRandom;

/**
 * 生成 随机字符串  工具类
 */
public class RandomUtil {

    // 去除 歧义 字母及数字
    private static final String[] baseString = {"a", "b", "c", "d", "e", "f", "g", "h", "j", "k", "m", "n", "p", "q", "w", "x", "y",
            "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "M", "N", "P", "Q", "W", "X", "Y",
            "2", "3", "4", "5", "6", "7", "8"};

    public static String randomString(int length) {
        //  return randomString(Arrays.toString(baseString), length);
        return randomString(baseString, length);
    }

    public static String randomString(String baseString, int length) {
        if (StringUtils.isBlank(baseString)) {
            return "";
        } else {
            StringBuilder sb = new StringBuilder(length);
            if (length < 1) {
                length = 1;
            }

            int baseLength = baseString.length();


            for (int i = 0; i < length; ++i) {
                int number = randomInt(baseLength);
                sb.append(baseString.charAt(number));
            }

            return sb.toString();
        }
    }

    //随机获取8位字符串  共有 41!/ (41-8)! 种结果   百万亿
    public static String randomString(String[] baseString, int length) {

        StringBuffer sb = new StringBuffer(length);
        if (length < 1) {
            length = 1;
        }
        int baseLength = baseString.length;

        for (int i = 0; i < length; ++i) {
            int number = randomInt(baseLength);
            sb.append(baseString[number]);
        }
        return sb.toString();
    }

    /**
     * 多线程下使用 ThreadLocalRandom 产生随机数时 确保随机数不重复 且比Random 效率更高
     * ThreadLocalRandom.current().nextInt()
     */
    public static int randomInt(int limit) {
        return getRandom().nextInt(limit);
    }

    public static ThreadLocalRandom getRandom() {
        return ThreadLocalRandom.current();
    }
}
